package cn.gpnusz.ucloudteach.service.live;

import cn.dev33.satoken.stp.StpUtil;
import cn.gpnusz.ucloudteach.common.CommonResp;
import cn.gpnusz.ucloudteach.config.AgoraConfig;
import cn.gpnusz.ucloudteach.entity.Admin;
import cn.gpnusz.ucloudteach.entity.ApplyTokenReq;
import cn.gpnusz.ucloudteach.entity.LiveContent;
import cn.gpnusz.ucloudteach.entity.LiveTokenResp;
import cn.gpnusz.ucloudteach.service.course.CourseMemberService;
import cn.gpnusz.ucloudteach.service.course.CourseService;
import cn.gpnusz.ucloudteach.service.user.SuperAdminService;
import cn.gpnusz.ucloudteach.util.token.media.RtcTokenBuilder;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

/**
 * @author h0ss
 * @description 直播token获取
 * @date 2022/4/5 - 16:26
 */
@Service
public class LiveTokenServiceImpl {

    private static final int EXPIRATION_TIME_IN_SECONDS = 300;

    @Resource
    private AgoraConfig agoraConfig;

    @Resource
    private CourseMemberService courseMemberService;

    @Resource
    private LiveTokenServiceImpl liveTokenService;

    @Resource
    private CourseService courseService;

    @Resource
    private SuperAdminService adminService;

    /**
     * 获取直播间token信息
     *
     * @param applyTokenReq : 申请信息
     * @return : cn.gpnusz.ucloudteach.common.CommonResp<cn.gpnusz.ucloudteach.entity.LiveTokenResp>
     * @author h0ss
     */
    public CommonResp<LiveTokenResp> getToken(ApplyTokenReq applyTokenReq) {
        CommonResp<LiveTokenResp> resp = new CommonResp<>();
        String channelName = applyTokenReq.getChannel();
        RtcTokenBuilder.Role role = applyTokenReq.getPublish() ? RtcTokenBuilder.Role.Role_Publisher : RtcTokenBuilder.Role.Role_Subscriber;
        int timestamp = (int) (System.currentTimeMillis() / 1000 + EXPIRATION_TIME_IN_SECONDS);
        RtcTokenBuilder token = new RtcTokenBuilder();
        String result = token.buildTokenWithUid(agoraConfig.APP_ID, agoraConfig.CERT, channelName, 0, role, timestamp);
        String roleResult = applyTokenReq.getPublish() ? "host" : "audience";
        LiveTokenResp ltr = new LiveTokenResp(result, channelName, 0, roleResult);
        resp.setContent(ltr);
        return resp;
    }

    /**
     * 学生获取token
     *
     * @param applyTokenReq : 申请信息
     * @return : cn.gpnusz.ucloudteach.common.CommonResp<cn.gpnusz.ucloudteach.entity.LiveTokenResp>
     * @author h0ss
     */
    public CommonResp<LiveTokenResp> stuGetToken(ApplyTokenReq applyTokenReq) {
        CommonResp<LiveTokenResp> resp = new CommonResp<>();
        resp.setSuccess(false);
        if (applyTokenReq == null) {
            return resp;
        }
        // 判断用户是否有获取token的权限【是否学员】
        Boolean isMember = courseMemberService.checkMember(applyTokenReq.getCourseId());
        if (!isMember) {
            return resp;
        }
        // 设置为观众角色
        applyTokenReq.setPublish(Boolean.FALSE);
        // 通过courseId获取channel信息 【这里注意做md5+盐处理一下】
        String channel = DigestUtils.md5DigestAsHex(Long.toString(applyTokenReq.getCourseId()).getBytes(StandardCharsets.UTF_8));
        applyTokenReq.setChannel(channel);
        // 开始生成token
        return liveTokenService.getToken(applyTokenReq);
    }

    /**
     * 教师获取token
     *
     * @param applyTokenReq : 申请信息
     * @return : cn.gpnusz.ucloudteach.common.CommonResp<cn.gpnusz.ucloudteach.entity.LiveTokenResp>
     * @author h0ss
     */
    public CommonResp<LiveTokenResp> teaGetToken(ApplyTokenReq applyTokenReq) {
        CommonResp<LiveTokenResp> resp = new CommonResp<>();
        resp.setSuccess(false);
        // 根据id查询用户名
        Long userId = StpUtil.getLoginIdAsLong();
        Admin info = adminService.getInfoById(userId);
        // 判断用户是否为开课教师
        if (info == null) {
            return resp;
        }
        Boolean isTeacher = courseService.checkTeacher(info.getUsername(), applyTokenReq.getCourseId());
        if (!isTeacher) {
            return resp;
        }
        // 可推流
        applyTokenReq.setPublish(Boolean.TRUE);
        // 通过courseId获取channel信息 【这里注意做md5+盐处理一下】
        String channel = applyTokenReq.getChannel();
        if (applyTokenReq.getChannel() == null) {
            channel = DigestUtils.md5DigestAsHex(Long.toString(applyTokenReq.getCourseId()).getBytes(StandardCharsets.UTF_8));
        }
        applyTokenReq.setChannel(channel);
        // 开始生成token
        return liveTokenService.getToken(applyTokenReq);
    }
}
